/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年9月24日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.scattered2.newInstance;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * @Type DO
 * @Desc
 * @author 52489
 * @date 2019年9月24日
 * @Version V1.0
 */
public class DO {
    public static void main(String[] args) {
        // 第一种new
        TestObject testObject = new TestObject();
        testObject.setName("testObject");
        testObject.sayHello();
        try {
            // 第二种 class.forName
            TestObject testObject2 = (TestObject) Class.forName("test.scattered2.newInstance.TestObject").newInstance();
            testObject2.setName("testObject2");
            testObject2.sayHello();

            // 第三种 使用Constructor类的newInstance方法 } → 调用了构造函数

            Constructor<TestObject> constructor = TestObject.class.getConstructor();
            TestObject testObject3 = constructor.newInstance();
            testObject3.setName("testObject3");
            testObject3.sayHello();

            // 第四种 使用clone方法 } → 没有调用构造函数
            TestObject testObject4 = (TestObject) testObject.clone();
            testObject4.setName("testObject4");
            testObject4.sayHello();

            // 第四种 序列化反序列化
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
            out.writeObject(testObject4);
            out.close();
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
            TestObject testObject5 = (TestObject) in.readObject();
            testObject5.setName("testObject5");
            testObject5.sayHello();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
